import json
import os


def process_json_data(json_data):
    """处理JSON数据，提取dailyItems中的flowList数据"""
    result = []

    # 确保data和dailyItems存在
    if 'data' in json_data and 'dailyItems' in json_data['data']:
        daily_items = json_data['data']['dailyItems']

        # 遍历dailyItems中的每一天
        for daily_item in daily_items:
            if 'flowList' in daily_item:
                flow_list = daily_item['flowList']

                # 遍历flowList中的每一笔交易
                for flow in flow_list:
                    # 提取需要的字段
                    transaction = {
                        'bizTime': flow.get('bizTime', ''),
                        'categoryName': flow.get('categoryName', ''),
                        'amount': flow.get('amount', 0),
                        'comment': flow.get('comment', ''),
                        'recType': flow.get('recType',''),
                        'categoryId': flow.get('categoryId', '')
                    }
                    result.append(transaction)

    return result


def main():
    # 输入和输出文件路径
    input_file = 'wacai.json'
    output_file = 'wacai_output.json'

    # 读取JSON文件
    try:
        with open(input_file, 'r', encoding='utf-8') as f:
            json_data = json.load(f)
    except FileNotFoundError:
        print(f"错误: 找不到输入文件 '{input_file}'")
        return
    except json.JSONDecodeError:
        print(f"错误: '{input_file}' 不是有效的JSON文件")
        return

    # 处理数据
    processed_data = process_json_data(json_data)

    # 输出到文件
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(processed_data, f, ensure_ascii=False, indent=2)
        print(f"处理完成，结果已保存到 '{output_file}'")
    except Exception as e:
        print(f"保存结果时出错: {e}")


if __name__ == "__main__":
    main()
